package services

import (
	"fmt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"strconv"

	"github.com/jinzhu/copier"
	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetChinaCity() (*api_models.GetChinaCityResp, error) {
	fName := "GetChinaCity"
	c, err := cache.GetChinaCity()
	if err == nil {
		c.From = "cache"
		return c, nil
	}
	list, err := db_main.GetChinaCitysParam(map[string]interface{}{"status": 1})
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	province := make([]*models_main.ChinaCity, 0)
	cityMap := make(map[string][]*models_main.ChinaCity)
	districtMap := make(map[string][]*models_main.ChinaCity)
	for i := range list {
		if list[i].Level == "province" {
			province = append(province, list[i])
			continue
		}
		if list[i].Level == "city" {
			pAdCode, _ := strconv.ParseInt(list[i].Adcode, 10, 64)
			pAdCodeStr := strconv.FormatInt(pAdCode/10000*10000, 10) //取得省的adcode
			if _, ok := cityMap[pAdCodeStr]; !ok {
				cityMap[pAdCodeStr] = make([]*models_main.ChinaCity, 0)
			}
			cityMap[pAdCodeStr] = append(cityMap[pAdCodeStr], list[i])
			continue
		}
		if _, ok := districtMap[list[i].Citycode]; !ok {
			districtMap[list[i].Citycode] = make([]*models_main.ChinaCity, 0)
		}
		districtMap[list[i].Citycode] = append(districtMap[list[i].Citycode], list[i])
	}

	resp := &api_models.GetChinaCityResp{From: "data"}
	resp.Provices = make([]*api_models.Provice, 0)
	err = copier.Copy(&resp.Provices, &province)
	if err != nil {
		return nil, err
	}
	for i := range resp.Provices {
		resp.Provices[i].Citys = make([]*api_models.City, 0)
		if val, ok := cityMap[resp.Provices[i].Adcode]; ok {
			err = copier.Copy(&resp.Provices[i].Citys, &val)
			if err != nil {
				fmt.Printf("%s %s\n", util.Convert(fName), err.Error())
				continue
			}
			for j := range resp.Provices[i].Citys {
				resp.Provices[i].Citys[j].District = make([]*models_main.ChinaCity, 0)
				if _, ok := districtMap[resp.Provices[i].Citys[j].Citycode]; ok {
					resp.Provices[i].Citys[j].District = districtMap[resp.Provices[i].Citys[j].Citycode]
				}
			}
		}
	}
	cache.SetChinaCity(resp)
	return resp, nil
}

func (s *Service) GetAndroidPatch(baseCode int) ([]*api_models.AndroidPatchResp, error) {
	var (
		err       error
		fName     = "GetAndroidPatch"
		dbQuery   []*models_main.AppPatch
		list      []*api_models.AndroidPatchResp
		condition = map[string]interface{}{
			"base_code": baseCode,
		}
	)

	if dbQuery, err = db_main.GetAndroidPatchParam(condition, "base_code desc"); err != nil {
		return nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
	}

	if len(dbQuery) > 0 {
		for _, patch := range dbQuery {
			list = append(list, &api_models.AndroidPatchResp{
				BaseCode: patch.BaseCode,
				PatchUrl: patch.PatchUrl,
				PatchID:  patch.PatchID,
			})
		}
	}

	return list, nil
}
